//
//  HsFloatAudioPlayerView.m
//  TestIos
//
//  Created by hs on 2020/10/15.
//  Copyright © 2020 tengfei. All rights reserved.
//

#import "HsFloatAudioPlayerView.h"
#import "Masonry.h"

#define content_corner_radius  float_player_H/2


@interface HsFloatAudioPlayerView ()

@property (nonatomic, assign) CGPoint startLocation;

@property(nonatomic, strong) UIButton *playControlBtn;

@property(nonatomic, strong) UIButton *closeBtn;

//动态播放视图
@property(nonatomic, strong) UIView *tempView;

@property (nonatomic, strong) CALayer *myLayer;


/** 阴影视图 */
@property (nonatomic, strong) UIView *shadowView;


/** 第一个背景直角图  */
@property (nonatomic, strong) UIView *firstBackView;

/** 第2个背景直角图  */
@property (nonatomic, strong) UIView *secondBackView;



@end


@implementation HsFloatAudioPlayerView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.userInteractionEnabled = YES;

        [self addSubview:self.shadowView];
        [self.shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.mas_equalTo(0);
        }];
        
        
        [self addSubview:self.firstBackView];
        [self.firstBackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(float_player_H);
        }];
        
        [self addSubview:self.secondBackView];
        [self.secondBackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(float_player_H);
        }];
        
        
        
        [self addSubview:self.tempView];
        
        [self addJumpView];
        
        [self addSubview:self.playControlBtn];
        [self addSubview:self.closeBtn];
        
        [self.playControlBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.tempView.mas_right);
            make.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(float_player_H);
        }];
        
        [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.playControlBtn.mas_right);
            make.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(float_player_H);
        }];
        
        [self bindData];
    }
    return self;
}

- (void)bindData {
//    @weakify(self);
//    [RACObserve([HsLCPlayerTool shareInstance], audioPlayStatus) subscribeNext:^(id  _Nullable x) {
//        @strongify(self);
//        [self updateViewWithPlayStatus:x];
//    }];
}

- (void)updateViewWithPlayStatus:(NSString *)playStatus {
    
    NSLog(@"float view play status %@", playStatus);

//    NSString *imageName = [playStatus isEqualToString:Hs_audio_paly_status_play_str] ? @"lczq_control_pause_icon" : @"lczq_control_play_icon";
//    [self.playControlBtn setImage:[UIImage imageNamed:imageName inBundleName:HsLCManager.bundleName forClass:HsLCManager.class] forState:UIControlStateNormal];
//
//
//    if ([playStatus isEqualToString:Hs_audio_paly_status_play_str]) {
//        [self pauseLayer:self.myLayer];
//        [self resumeLayer:self.myLayer];
//    } else {
//        [self pauseLayer:self.myLayer];
//
//    }
    
    
}


#pragma mark -- lazyload
 
- (UIView *)shadowView {
    if (!_shadowView) {
        _shadowView = [[UIView alloc] initWithFrame:CGRectZero];
        _shadowView.backgroundColor = [UIColor whiteColor];
        _shadowView.layer.cornerRadius = content_corner_radius;
        _shadowView.layer.masksToBounds = NO;
        _shadowView.layer.shadowColor   = [UIColor blackColor].CGColor;
        _shadowView.layer.shadowOffset  = CGSizeMake(0, 0);
        _shadowView.layer.shadowOpacity = 0.2;
        _shadowView.layer.shadowRadius  = 5;
    }
    return _shadowView;
}
- (UIView *)firstBackView {
    if (!_firstBackView) {
        _firstBackView = [[UIView alloc] initWithFrame:CGRectZero];
        _firstBackView.backgroundColor = [UIColor whiteColor];
    }
    return _firstBackView;
}
- (UIView *)secondBackView {
    if (!_secondBackView) {
        _secondBackView = [[UIView alloc] initWithFrame:CGRectZero];
        _secondBackView.backgroundColor = [UIColor whiteColor];
    }
    return _secondBackView;
}



- (UIButton *)playControlBtn {
    if (!_playControlBtn) {
        _playControlBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
//        UIImage *tempImage = [UIImage imageNamed:@"lczq_control_play_icon" inBundleName:HsLCManager.bundleName forClass:HsLCManager.class];
        
        UIImage *tempImage = [UIImage imageNamed:@"lczq_control_play_icon"];
        [_playControlBtn setImage:tempImage forState:UIControlStateNormal];
        [_playControlBtn addTarget:self action:@selector(handleplayControlBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playControlBtn;
}
- (void)handleplayControlBtn:(id)sender {
    if ([self.delegate respondsToSelector:@selector(clickFloatBtnWithIndex:)]) {
        [self.delegate clickFloatBtnWithIndex:1];
    }
}


- (UIButton *)closeBtn {
    if (!_closeBtn) {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        UIImage *tempImage = [UIImage imageNamed:@"lczq_close_icon"];
        
        [_closeBtn setImage:tempImage forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(handlecloseBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}
- (void)handlecloseBtn:(id)sender {
    
    if ([self.delegate respondsToSelector:@selector(clickFloatBtnWithIndex:)]) {
        [self.delegate clickFloatBtnWithIndex:0];
    }
    
}


- (UIView *)tempView{
    if (!_tempView) {
        _tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
//        _tempView.backgroundColor = [UIColor cyanColor];
    }
    return _tempView;;
}


- (void)addJumpView {
    // 1.创建一个复制图层对象，设置复制层的属性
    CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
    
    // 1.1.设置复制图层中子层总数：这里包含原始层
    replicatorLayer.instanceCount = 3;
    // 1.2.设置复制子层偏移量，不包含原始层，这里是相对于原始层的x轴的偏移量
    replicatorLayer.instanceTransform = CATransform3DMakeTranslation(5, 0, 0);
    // 1.3.设置复制层的动画延迟事件
    replicatorLayer.instanceDelay = 0.1;
    // 1.4.设置复制层的背景色，如果原始层设置了背景色，这里设置就失去效果
    replicatorLayer.instanceColor = [UIColor redColor].CGColor;
    // 1.5.设置复制层颜色的偏移量
    replicatorLayer.instanceGreenOffset = -0.1;
    
    // 2.创建一个图层对象  单条柱形 (原始层)
//    CALayer *layer = [CALayer layer];
//    // 2.1.设置layer对象的位置
//    layer.position = CGPointMake(5, 30);
//    // 2.2.设置layer对象的锚点
//    layer.anchorPoint = CGPointMake(0, 1);
//    // 2.3.设置layer对象的位置大小
//    layer.bounds = CGRectMake(0, 0, 5, 20);
//    // 2.5.设置layer对象的颜色
//    layer.backgroundColor = [UIColor whiteColor].CGColor;
    
    // 3.创建一个基本动画
    CABasicAnimation *basicAnimation = [CABasicAnimation animation];
    // 3.1.设置动画的属性
    basicAnimation.keyPath = @"transform.scale.y";
    // 3.2.设置动画的属性值
    basicAnimation.toValue = @0.1;
    // 3.3.设置动画的重复次数
    basicAnimation.repeatCount = MAXFLOAT;
    // 3.4.设置动画的执行时间
    basicAnimation.duration = 0.3;
    // 3.5.设置动画反转
    basicAnimation.autoreverses = YES;
    
    //解决离屏停止
    basicAnimation.removedOnCompletion = NO;
    
    // 4.将动画添加到layer层上
    [self.myLayer addAnimation:basicAnimation forKey:nil];
    
    // 5.将layer层添加到复制层上
    [replicatorLayer addSublayer:self.myLayer];
    
    // 6.将复制层添加到view视图层上
    [self.tempView.layer addSublayer:replicatorLayer];
}


- (CALayer *)myLayer {
    if (!_myLayer) {
        _myLayer = [CALayer layer];
        // 2.1.设置layer对象的位置
        _myLayer.position = CGPointMake(15, 23);
        // 2.2.设置layer对象的锚点
        _myLayer.anchorPoint = CGPointMake(0, 1);
        // 2.3.设置layer对象的位置大小
        _myLayer.bounds = CGRectMake(0, 0, 2, 10);
        // 2.5.设置layer对象的颜色
        _myLayer.backgroundColor = [UIColor whiteColor].CGColor;
    }
    return _myLayer;
}


-(void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

-(void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}


#pragma mark - move delegate
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:self];
    self.startLocation = pt;
    [[self superview] bringSubviewToFront:self];
}
 
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:self];
    float dx = pt.x - self.startLocation.x;
    float dy = pt.y - self.startLocation.y;
    CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
    //
    float halfx = CGRectGetMidX(self.bounds);
    newcenter.x = MAX(halfx, newcenter.x);
    newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x);
    //
    float halfy = CGRectGetMidY(self.bounds);
    newcenter.y = MAX(halfy, newcenter.y);
    newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y);
    //
    self.center = newcenter;
    
}
 
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint point = self.center;
    
    CGFloat finalY = point.y < SYS_STATUS_HEIGHT ? SYS_STATUS_HEIGHT : point.y;
    
    if (point.x>[self superview].frame.size.width/2.0) {
        [UIView animateWithDuration:0.2 animations:^{
            self.frame = CGRectMake([self superview].frame.size.width-self.frame.size.width, finalY, float_player_W, float_player_H);
        }];
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            self.frame = CGRectMake(0, finalY, float_player_W, float_player_H);
        }];
    }
}
 
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
 

@end
